package com.example.common;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * 跨域配置
 */
@Configuration
public class CorsConfig {

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        
        // 允许的源地址（当withCredentials为true时，不能使用通配符*）
        corsConfiguration.addAllowedOrigin("http://localhost:5173"); // 明确允许前端地址
        corsConfiguration.addAllowedOrigin("http://localhost:5175"); // 明确允许前端地址
        
        // 允许的请求头
        corsConfiguration.addAllowedHeader("*");
        
        // 允许的请求方法
        corsConfiguration.addAllowedMethod("GET");
        corsConfiguration.addAllowedMethod("POST");
        corsConfiguration.addAllowedMethod("PUT");
        corsConfiguration.addAllowedMethod("DELETE");
        corsConfiguration.addAllowedMethod("OPTIONS");
        
        // 允许携带凭证（重要：解决登录session问题）
        corsConfiguration.setAllowCredentials(true);
        
        // 预检请求的缓存时间
        corsConfiguration.setMaxAge(3600L);
        
        source.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(source);
    }
}